/*
* @(#)MaintHolidayGenerationAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.setup.web;

import java.sql.Connection;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.client.analyzer.DmsDocumentAnalyzer;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.setup.bean.HolidayRecord;
import com.dcivision.setup.dao.HolidayRecordDAObject;
import com.dcivision.setup.dao.WorkingCalendarDAObject;

/**
 * MaintHolidayGenerationAction.java
 * 
 * It handles the holiday generation
 * 
 * @author Weison Liang
 * @company DCIVision Limited
 * @creation date 30/03/2005
 * @version $Revision: 1.9.2.1 $
 */

public class MaintHolidayGenerationAction extends AbstractMaintAction  {

  public static final String REVISION = "$Revision: 1.9.2.1 $";

  protected static String MESSAGE_DUPLICATE_NAME= "setup.message.duplicate_name";
  protected static String MESSAGE_USER_CUSTOM="setup.message.user_custom";

  protected static String scannedUDFName = "";
  protected String parentID = "";
  protected String rootID = "";
  protected String docType = "";
  protected DmsDocumentAnalyzer documentAnalyzer = null;

  private String odmaProcess = "";

  public MaintHolidayGenerationAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.setup.dao.HolidayRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.SETUP_HOLIDAY_GENERATION);
  }

  /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintHolidayGenerationForm actionForm = (MaintHolidayGenerationForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    //get the working calendar list.
    this.getWorkingCalendarList(request);

    String opMode = actionForm.getOpMode();
    String navMode = actionForm.getNavMode();
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    return super.execute(mapping, form, request, response);
  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    HolidayRecordDAObject holidayRecordDAO = new HolidayRecordDAObject(sessionContainer,conn);
    MaintHolidayGenerationForm actionForm = (MaintHolidayGenerationForm) form;

    String []referenceAry=actionForm.getReferenceList();
log.debug("Generating public holidays ... " );
    if (!Utility.isEmpty(referenceAry)) {
      for (int i = 0; i < referenceAry.length; i++) {
        HolidayRecord holidayRecord = (HolidayRecord) holidayRecordDAO.getObjectByID(TextUtility.parseIntegerObj(referenceAry[i]));

        Calendar startCalendar = Utility.timestampToCalendar(holidayRecord.getStartDate());
        Calendar endCalendar = Utility.timestampToCalendar(holidayRecord.getEndDate());
        startCalendar.set(Calendar.YEAR, Integer.parseInt(actionForm.getYear()));
        endCalendar.set(Calendar.YEAR, Integer.parseInt(actionForm.getYear()));
        
        holidayRecord.setReferenceFlag(HolidayRecord.REFERENCE_TYPE_RECORD);
        holidayRecord.setStartDate(Utility.calendarToTimestamp(startCalendar));
        holidayRecord.setEndDate(Utility.calendarToTimestamp(endCalendar));
        try{
          holidayRecord = (HolidayRecord) holidayRecordDAO.insertObject(holidayRecord);
        }catch(ApplicationException appEx){
          // ignore the duplicate error for public holiday
        }
      }
    }
log.debug("Generating general holidays ...");    
    this.insertDateRecord(mapping,form,request,response);
//    this.commit(request);
//    holidayRecord.setYear(actionForm.getYear());
//    actionForm.setFormData(holidayRecord);
  }

  public void insertDateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response)throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
log.debug("Finished getting connection");
    HolidayRecordDAObject holidayRecordDAO = new HolidayRecordDAObject(sessionContainer,conn);
    MaintHolidayGenerationForm actionForm = (MaintHolidayGenerationForm) form;

    Integer workingCalendarID = Integer.valueOf(actionForm.getWorkingCalendarID());
    int year = Integer.parseInt(actionForm.getYear());
log.debug("Generating holiday for year "+year);
    String dayOff[] = new String[7];
    try {
      for(int i = 1; i <= dayOff.length ; i++){
        dayOff[i-1] = BeanUtils.getProperty(actionForm, "dayOff"+i);
log.debug("\tdayOff["+(i-1)+"]="+dayOff[i-1]);
      }
    } catch (Exception e) {
log.error(e.getMessage(), e);
      throw new ApplicationException(e);
    }
    
    Calendar startCalendar = new GregorianCalendar();
    startCalendar.set(Calendar.YEAR, year);
    startCalendar.set(Calendar.MONTH, 0);
    startCalendar.set(Calendar.DAY_OF_YEAR, 1);
    startCalendar.set(Calendar.HOUR_OF_DAY, 0);
    startCalendar.set(Calendar.MINUTE, 0);
    startCalendar.set(Calendar.SECOND, 0);
    startCalendar.set(Calendar.MILLISECOND, 0);
log.debug("Start at "+TextUtility.formatDate(startCalendar.getTime(), "yyyy-MM-dd"));
    for(;startCalendar.get(Calendar.YEAR)==year;startCalendar.add(Calendar.DAY_OF_YEAR, 1)){
log.debug("Processing "+TextUtility.formatDate(startCalendar.getTime(), "yyyy-MM-dd"));
      int weekday = startCalendar.get(Calendar.DAY_OF_WEEK);
      if (Utility.isEmpty(dayOff[weekday-1])) { 
log.debug("\tIgnored ...");
        continue; 
      } else if (HolidayRecord.DAY_OFF_HALF.equals(dayOff[weekday-1])){ 
        startCalendar.set(Calendar.HOUR_OF_DAY, 12);
      }
      Calendar endCalendar = (Calendar)startCalendar.clone();
      endCalendar.set(Calendar.HOUR_OF_DAY, 23);
      endCalendar.set(Calendar.MINUTE, 59);
      endCalendar.set(Calendar.SECOND, 59);
//      endCalendar.set(Calendar.MILLISECOND, 999);
      
      HolidayRecord holidayRecord = new HolidayRecord();
      holidayRecord.setWorkingCalendarID(workingCalendarID);
      holidayRecord.setHolidayName(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.generation.day_of_week."+weekday) + " ("+TextUtility.formatTimestampToDBDate(Utility.calendarToTimestamp(startCalendar)).substring(0,10)+")");
      holidayRecord.setReferenceFlag(HolidayRecord.REFERENCE_TYPE_RECORD);
      holidayRecord.setHolidayType(HolidayRecord.HOLIDAY_TYPE_GENERAL);
      holidayRecord.setStartDate(Utility.calendarToTimestamp(startCalendar));
      holidayRecord.setEndDate(Utility.calendarToTimestamp(endCalendar));
      try{
        holidayRecord = (HolidayRecord) holidayRecordDAO.insertObject(holidayRecord);
      }catch(ApplicationException appEx){
        throw appEx;
      }
log.debug("\tCreated "+TextUtility.formatDate(startCalendar.getTime(), "yyyy-MM-dd HH:mm:ss") + " - " + TextUtility.formatDate(endCalendar.getTime(), "yyyy-MM-dd HH:mm:ss") + " ["+dayOff[weekday-1]+"]");
      
      startCalendar.set(Calendar.HOUR_OF_DAY, 0);
    }
  }

  /**
   * get the working calendar list.
   * @param request
   * @throws ApplicationException
   */
  private void getWorkingCalendarList(HttpServletRequest request) throws ApplicationException {
    WorkingCalendarDAObject workingCalDAO = new WorkingCalendarDAObject(this.getSessionContainer(request), this.getConnection(request));
    List workingCalList = workingCalDAO.getFullList();
    request.setAttribute("WORKING_CALENDAR_LIST", workingCalList);
  }
}
